package cn.linlane.config;

import cn.linlane.entity.errors.MyError;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.ui.ModelMap;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author cheng
 * @date 2018-05-03 11:32
 * 自定义认证过滤器，未认证返回401
 */
public class LoginFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        Subject subject = SecurityUtils.getSubject();

        if(null != subject && subject.isAuthenticated()){
            return true;
        }
        ModelMap modelMap = new ModelMap();
        modelMap.put("httpCode", MyError.USER_NOT_LOGIN.getErrorCode());
        modelMap.put("msg",  MyError.USER_NOT_LOGIN.getMessage());
        modelMap.put("timestamp", System.currentTimeMillis());
        byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
        response.setContentType("application/json;charset=UTF-8");
        response.getOutputStream().write(bytes);
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
